package com.minelx.statementsplus.split;

import com.minelx.statementsplus.MajorSql;
import com.minelx.statementsplus.Proxy;

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ProxiesSplitter implements MajorSplitter {

	private final Proxy provinces;

	private final Function<int[], MajorSql> toNewSqlBuilder;

	private final int[] sourceProxyIds;

	public ProxiesSplitter(int[] sourceProxyIds, Function<int[], MajorSql> toNewSqlBuilder) {
		provinces = Proxy.provinces();
		this.toNewSqlBuilder = toNewSqlBuilder;
		this.sourceProxyIds = sourceProxyIds;
	}

	@Override
	public List<MajorSql> split() {
		Proxy sourceProxy = provinces.path(sourceProxyIds);
		return sourceProxy.children().stream()
				.map(Proxy::code)
				.map(childCode -> appendItemForArray(sourceProxyIds, childCode))
				.map(toNewSqlBuilder)
				.collect(Collectors.toList());
	}

	private int[] appendItemForArray(int[] source, int appended) {
		int[] result = Arrays.copyOf(source, source.length + 1);
		result[result.length - 1] = appended;
		return result;
	}
}
